<template>
  <view class="music-player-container">
    <!-- 加载状态提示 -->
    <view v-if="isLoading" class="loading-overlay">
      <view class="loading-content">
        <view class="loading-spinner"></view>
        <text class="loading-text">加载音乐中...</text>
      </view>
    </view>

    <!-- 专辑封面区域 -->
    <view class="album-section">
      <view class="vinyl-record">
        <image src="/static/idcs.png" class="vinyl-image" mode="aspectFit"></image>
        <view class="album-cover-container" :class="{'rotating': isPlaying}">
          <image :src="albumCover || '/static/images/default-cover.png'" class="album-cover" mode="aspectFill"></image>
        </view>
      </view>
      
      <view class="tonearm" :class="{'tonearm-playing': isPlaying}">
        <image src="/static/needle.png" class="needle-image" mode="aspectFit"></image>
      </view>
      
      <view class="album-overlay"></view>
      
      <!-- 歌曲信息 -->
      <view class="song-info">
        <text class="song-title">{{ songTitle }}</text>
        <text class="song-artist">{{ songArtist }}</text>
      </view>
    </view>
    
    <!-- 歌词区域 -->
    <view class="lyrics-section">
      <scroll-view class="lyrics-container" scroll-y :scroll-top="scrollTop" scroll-with-animation>
        <view class="lyrics-content">
          <text v-if="!lyrics.length" class="lyrics-line">{{ lyricsLoadingText }}</text>
          <text 
            v-for="(line, index) in lyrics" 
            :key="index" 
            :class="['lyrics-line', {'active': currentLineIndex === index}]"
          >
            {{ line.text }}
          </text>
        </view>
      </scroll-view>
    </view>
    
    <!-- 进度条 -->
    <view class="progress-section">
      <view class="time-display">
        <text class="time-text">{{ currentTimeFormatted }}</text>
        <text class="time-text">{{ durationFormatted }}</text>
      </view>
      <view class="progress-bar" @tap="seek">
        <view class="progress-bg"></view>
        <view class="progress-fill" :style="{ width: progressPercent + '%' }"></view>
        <view class="progress-handle" :style="{ left: progressPercent + '%' }"></view>
      </view>
    </view>
    
    <!-- 控制按钮 -->
    <view class="controls-section">
      <view @tap="toggleShuffle" :class="['control-btn', {'active': isShuffleOn}]">
        <text class="uni-icon">{{ '\ue66b' }}</text>
      </view>
      <view @tap="playPrevious" class="control-btn">
        <text class="uni-icon">{{ '\ue66a' }}</text>
      </view>
      <view @tap="togglePlayPause" 
        :class="['play-btn', {'disabled': !canPlay || isLoading}]">
        <text class="uni-icon">{{ isPlaying ? '\ue66c' : '\ue669' }}</text>
      </view>
      <view @tap="playNext" class="control-btn">
        <text class="uni-icon">{{ '\ue66d' }}</text>
      </view>
      <view @tap="toggleRepeat" :class="['control-btn', {'active': repeatMode !== 'off'}]">
        <text class="uni-icon">{{ repeatMode === 'one' ? '\ue66f' : '\ue66e' }}</text>
      </view>
    </view>

    <!-- 相似歌曲推荐 -->
    <!-- 
    <view v-if="similarSongs.length > 0" class="similar-section">
      <text class="similar-title">相似歌曲推荐</text>
      <view class="similar-list">
        <view v-for="(song, index) in similarSongs" :key="song.id" 
          @tap="playSimilarSong(song.id)"
          class="similar-item">
          <image :src="song.album?.picUrl || '/static/images/default-cover.png'" class="similar-cover" mode="aspectFill"></image>
          <view class="similar-info">
            <text class="similar-name">{{ song.name }}</text>
            <text class="similar-artist">{{ getSongArtists(song) }}</text>
          </view>
        </view>
      </view>
    </view>
    -->
  </view>
</template>

<script>
import { songDetail, songUrl, songLyric, songSimi } from '../../common/api.js';

export default {
  data() {
    return {
// 播放器状态
      songTitle: '未知歌曲',
      songArtist: '未知艺术家',
      albumCover: '',
      lyrics: [],
      currentTime: 0,
      duration: 0, // 秒
      isPlaying: false,
      currentLineIndex: -1,
      scrollTop: 0,
      lineHeight: 40,
      songId: null,
      audioUrl: '',
      audioContext: null,
      similarSongs: [], // 保留变量，但不再使用
      isLoading: true,
      canPlay: false,
      lyricsLoadingText: '加载歌词中...',
      isShuffleOn: false,
      repeatMode: 'off', // 'off', 'all', 'one'
      playHistory: [],
      currentSongIndex: -1,
      timer: null,
      hoverTime: 0
    };
  },
  computed: {
    progressPercent() {
      return (this.currentTime / this.duration) * 100 || 0;
    },
    currentTimeFormatted() {
      return this.formatTime(this.currentTime);
    },
    durationFormatted() {
      return this.formatTime(this.duration);
    },
    hoverTimeFormatted() {
      return this.formatTime(this.hoverTime);
    }
  },
  onLoad(options) {
    // 获取歌曲ID
    this.songId = options.songId || options.id || '1824045033'; // 优先使用从歌单列表传来的songId
    console.log('接收到的歌曲ID:', this.songId);
    
    // 初始化音频上下文
    this.initAudioContext();
    
    // 加载歌曲数据
    this.loadSong(this.songId);
  },
  onUnload() {
    // 停止音频
    if (this.audioContext) {
      this.audioContext.stop();
    }
    
    // 清除定时器
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null;
    }
  },
  onShow() {
    // 页面显示时，同步最新的播放状态到存储
    if (this.songId && this.songTitle) {
      this.updatePlayingStatusSimple();
    }
  },
  methods: {
    // 初始化音频上下文
    initAudioContext() {
      this.audioContext = uni.createInnerAudioContext();
      
      // 监听音频事件
      this.audioContext.onCanplay(() => {
        this.canPlay = true;
      });
      
      this.audioContext.onPlay(() => {
        this.isPlaying = true;
        this.startTimer();
        this.updatePlayingStatusSimple();
      });
      
      this.audioContext.onPause(() => {
        this.isPlaying = false;
        this.clearTimer();
        this.updatePlayingStatusSimple();
      });
      
      this.audioContext.onStop(() => {
        this.isPlaying = false;
        this.clearTimer();
        this.updatePlayingStatusSimple();
      });
      
      this.audioContext.onEnded(() => {
        this.handleSongEnd();
      });
      
      this.audioContext.onError((err) => {
        console.error('音频播放错误:', err);
        this.handleAudioError();
        this.updatePlayingStatusSimple();
      });
      
      // 获取音频时长
      this.audioContext.onTimeUpdate(() => {
        this.currentTime = this.audioContext.currentTime;
        this.duration = this.audioContext.duration || 0;
        this.updateCurrentLyric();
      });
    },
    
    // 开始计时器（备用，如果onTimeUpdate不够稳定）
    startTimer() {
      this.clearTimer();
      this.timer = setInterval(() => {
        if (this.audioContext && this.isPlaying) {
          this.currentTime = this.audioContext.currentTime;
          this.updateCurrentLyric();
        }
      }, 100);
    },
    
    // 清除计时器
    clearTimer() {
      if (this.timer) {
        clearInterval(this.timer);
        this.timer = null;
      }
    },
    
    // 加载歌曲数据
    async loadSong(id, autoplay = false) {
      try {
        this.isLoading = true;
        this.canPlay = false;
        this.lyricsLoadingText = '加载歌词中...';
        
        // 暂停当前播放
        if (this.audioContext && this.isPlaying) {
          this.audioContext.pause();
          this.isPlaying = false;
        }
        
        // 获取歌曲详情
        const detailRes = await songDetail(id);
        const songInfo = detailRes.data.songs[0];
        
        if (songInfo) {
          this.songTitle = songInfo.name;
          this.songArtist = songInfo.ar.map(artist => artist.name).join(', ');
          this.albumCover = songInfo.al.picUrl;
          this.duration = songInfo.dt / 1000; // 毫秒转秒
          
          // 更新播放历史
          if (this.currentSongIndex >= 0) {
            this.playHistory = this.playHistory.slice(0, this.currentSongIndex + 1);
          }
          this.playHistory.push(id);
          this.currentSongIndex = this.playHistory.length - 1;
          
          // 更新当前播放信息到存储
          this.updatePlayingStatus(id, songInfo);
        }
        
        // 获取歌曲URL
        const urlRes = await songUrl(id);
        const urlData = urlRes.data.data[0];
        
        if (urlData && urlData.url) {
          this.audioUrl = urlData.url;
          if (this.audioContext) {
            this.audioContext.src = this.audioUrl;
            
            if (autoplay) {
              this.audioContext.autoplay = true;
            }
          }
        } else {
          console.error('获取歌曲URL失败');
          this.lyricsLoadingText = '获取歌曲失败，请尝试其他歌曲';
        }

// 获取歌词
        await this.fetchLyrics(id);
        
        /* 注释掉获取相似歌曲的部分
        // 获取相似歌曲
        await this.fetchSimilarSongs(id);
        */
        
        this.songId = id;
      } catch (error) {
        console.error('加载歌曲数据失败:', error);
        this.lyricsLoadingText = '加载失败，请检查网络连接';
      } finally {
        this.isLoading = false;
      }
    },
    
    // 更新当前播放状态
    updatePlayingStatus(id, songInfo) {
      try {
        uni.setStorageSync('playing_song_info', {
          id: id,
          name: songInfo.name,
          artist: songInfo.ar.map(artist => artist.name).join(', '),
          albumCover: songInfo.al.picUrl,
          isPlaying: this.isPlaying
        });
      } catch (e) {
        console.error('保存播放状态失败', e);
      }
    },
    
    // 处理音频错误
    handleAudioError() {
      this.canPlay = false;
      this.isPlaying = false;
      this.lyricsLoadingText = '音频加载失败，请尝试其他歌曲';
      console.error('音频加载失败');
    },
    
    // 歌曲结束处理
    handleSongEnd() {
      this.isPlaying = false;
      this.currentTime = 0;
      
      // 根据重复模式决定下一步操作
      if (this.repeatMode === 'one') {
        // 单曲循环
        if (this.audioContext) {
          this.audioContext.seek(0);
          this.audioContext.play();
        }
      } else if (this.repeatMode === 'all' || this.isShuffleOn) {
        // 全部循环或随机播放
        this.playNext();
      }
    },
    
    // 获取歌词
    async fetchLyrics(id) {
      try {
        const res = await songLyric(id);
        const data = res.data;
        
        if (data.code === 200 && data.lrc && data.lrc.lyric) {
          this.parseLyrics(data.lrc.lyric);
    } else {
          this.showErrorLyrics('未找到歌词');
    }
  } catch (error) {
    console.error('获取歌词失败:', error);
        this.showErrorLyrics('获取歌词失败');
      }
    },
    
    /* 注释掉获取相似歌曲的函数
    // 获取相似歌曲
    async fetchSimilarSongs(id) {
      try {
        const res = await songSimi(id);
        const data = res.data;
        
        if (data.code === 200 && data.songs) {
          this.similarSongs = data.songs.slice(0, 5); // 获取前5首相似歌曲
        } else {
          this.similarSongs = [];
        }
      } catch (error) {
        console.error('获取相似歌曲失败:', error);
        this.similarSongs = [];
      }
    },
    */

// 解析歌词
    parseLyrics(rawLyrics) {
  const lines = rawLyrics.split('\n');
  const parsedLyrics = [];
  
  lines.forEach(line => {
    // 匹配时间戳和歌词文本
    const timeRegex = /\[(\d{2}):(\d{2})\.(\d{2,3})\]/g;
    const text = line.replace(timeRegex, '').trim();
    
    if (text) {
      let match;
      while ((match = timeRegex.exec(line)) !== null) {
        const minutes = parseInt(match[1]);
        const seconds = parseInt(match[2]);
        const milliseconds = parseInt(match[3]);
        
            // 计算总秒数
            const timeInSeconds = minutes * 60 + seconds + (milliseconds / (match[3].length === 2 ? 100 : 1000));
        
        parsedLyrics.push({
          time: timeInSeconds,
          text
        });
      }
    }
  });
  
  // 按时间排序
  parsedLyrics.sort((a, b) => a.time - b.time);
      
      if (parsedLyrics.length === 0) {
        this.showErrorLyrics('暂无歌词');
      } else {
        this.lyrics = parsedLyrics;
      }
    },

// 显示错误歌词
    showErrorLyrics(message = '获取歌词失败') {
      this.lyrics = [
        { time: 0, text: message },
    { time: 5, text: "请检查网络连接或尝试其他歌曲" }
  ];
    },

// 切换播放/暂停状态
    togglePlayPause() {
      if (!this.audioContext || !this.audioUrl || !this.canPlay || this.isLoading) return;
  
      if (this.isPlaying) {
        this.audioContext.pause();
  } else {
        this.audioContext.play();
      }
      
      // 播放状态变化后更新存储
      this.$nextTick(() => {
        this.updatePlayingStatusSimple();
      });
    },
    
    // 切换随机播放
    toggleShuffle() {
      this.isShuffleOn = !this.isShuffleOn;
    },
    
    // 切换重复模式
    toggleRepeat() {
      if (this.repeatMode === 'off') {
        this.repeatMode = 'all';
      } else if (this.repeatMode === 'all') {
        this.repeatMode = 'one';
      } else {
        this.repeatMode = 'off';
      }
    },
    
    // 播放上一首
    playPrevious() {
      if (this.currentSongIndex > 0) {
        this.currentSongIndex--;
        this.loadSong(this.playHistory[this.currentSongIndex], true);
      }
    },
    
    // 播放下一首
    playNext() {
      /* 修改播放下一首的逻辑，移除相似歌曲部分 */
      if (this.currentSongIndex < this.playHistory.length - 1) {
        // 播放历史中的下一首
        this.currentSongIndex++;
        this.loadSong(this.playHistory[this.currentSongIndex], true);
      }
      /*
      else if (this.similarSongs.length > 0) {
        // 播放第一首相似歌曲
        this.playSimilarSong(this.similarSongs[0].id);
      }
      */
    },
    
    /* 注释掉播放相似歌曲的函数
    // 播放相似歌曲
    playSimilarSong(id) {
      this.loadSong(id, true);
    },
    
    // 获取歌手名字
    getSongArtists(song) {
      return song.artists?.map(artist => artist.name).join(', ') || '未知艺术家';
    },
    */

// 更新当前歌词
    updateCurrentLyric() {
      if (!this.lyrics.length) return;
      
      let index = -1;
  
  // 找到当前应该高亮的歌词行
      for (let i = 0; i < this.lyrics.length; i++) {
        if (i === this.lyrics.length - 1) {
      // 如果是最后一行，只要当前时间大于该行时间就高亮
          if (this.currentTime >= this.lyrics[i].time) {
            index = i;
      }
        } else if (this.currentTime >= this.lyrics[i].time && this.currentTime < this.lyrics[i + 1].time) {
      // 当前时间在这一行和下一行之间
          index = i;
      break;
    }
  }
  
  // 如果当前行有变化，则更新高亮和滚动
      if (index !== this.currentLineIndex) {
        this.currentLineIndex = index;
        this.scrollToCurrentLine(index);
      }
    },

// 滚动到当前行
    scrollToCurrentLine(index) {
      if (index < 0 || index >= this.lyrics.length) return;
      
      // 计算滚动位置，使当前行居中显示
      const viewportHeight = 360; // 歌词容器高度
      const lineHeight = this.lineHeight;
      
      // 计算当前行到顶部的距离，并减去一半视口高度使其居中
      this.scrollTop = Math.max(0, index * lineHeight - (viewportHeight / 2) + (lineHeight / 2));
    },

// 处理进度条点击
    seek(e) {
      if (!this.audioContext || !this.duration || !this.canPlay) return;
      
      // 获取点击位置相对于进度条的偏移
      const detail = e.touches[0];
      const pageX = detail.pageX;
      const pageY = detail.pageY;
      
      // 获取进度条元素
      const query = uni.createSelectorQuery().in(this);
      query.select('.progress-bar').boundingClientRect(data => {
        if (data) {
          const progressWidth = data.width;
          const progressLeft = data.left;
          
          // 计算点击位置相对于进度条的百分比
          const clickPosition = pageX - progressLeft;
          const percent = clickPosition / progressWidth;
          
          // 计算点击位置对应的时间并设置
          const newTime = percent * this.duration;
          this.audioContext.seek(Math.max(0, Math.min(newTime, this.duration)));
        }
      }).exec();
    },

// 格式化时间为 MM:SS
    formatTime(seconds) {
  const minutes = Math.floor(seconds / 60);
  const remainingSeconds = Math.floor(seconds % 60);
  return `${minutes.toString().padStart(2, '0')}:${remainingSeconds.toString().padStart(2, '0')}`;
    },
    
    // 更新播放状态到存储（简化版）
    updatePlayingStatusSimple() {
      try {
        uni.setStorageSync('playing_song_info', {
          id: this.songId,
          name: this.songTitle,
          artist: this.songArtist,
          albumCover: this.albumCover,
          isPlaying: this.isPlaying
        });
      } catch (e) {
        console.error('保存播放状态失败', e);
      }
    }
  }
};
</script>

<style>
.music-player-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  background-color: #181818;
  color: #ffffff;
  border-radius: 24rpx;
  overflow: hidden;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.7);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 100;
}

.loading-content {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 6rpx solid rgba(255, 255, 255, 0.1);
  border-radius: 50%;
  border-top-color: #3b82f6;
  animation: spin 1s linear infinite;
  margin-bottom: 20rpx;
}

.loading-text {
  font-size: 28rpx;
  color: #d1d5db;
}

/* 专辑封面区域 */
.album-section {
  position: relative;
  height: 550rpx;
  width: 100%;
  background: linear-gradient(135deg, rgba(59, 130, 246, 0.2), rgba(147, 51, 234, 0.2));
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding-bottom: 100rpx;
  overflow: hidden;
}

/* 黑胶唱片效果 */
.vinyl-record {
  width: 350rpx;
  height: 350rpx;
  position: relative;
  margin-bottom: 60rpx;
  z-index: 10;
}

.vinyl-image {
  position: absolute;
  width: 350rpx;
  height: 350rpx;
  z-index: 5;
}

.album-cover-container {
  position: absolute;
  width: 150rpx;
  height: 150rpx;
  border-radius: 50%;
  overflow: hidden;
  z-index: 10;
  box-shadow: 0 8rpx 30rpx rgba(0, 0, 0, 0.3);
  top: 100rpx;
  left: 100rpx;
}

.album-cover {
  width: 100%;
  height: 100%;
}

/* 唱针 */
.tonearm {
  position: absolute;
  top: 40rpx;
  right: 210rpx;
  width: 180rpx;
  height: 180rpx;
  z-index: 20;
  transform-origin: 30% 30%;
  transform: rotate(-25deg);
  transition: transform 0.5s ease;
}

.tonearm-playing {
  transform: rotate(-5deg);
}

.needle-image {
  width: 100%;
  height: 100%;
}

.album-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(to top, #181818, transparent);
}

.song-info {
  position: absolute;
  bottom: 20rpx;
  left: 0;
  right: 0;
  padding: 20rpx 40rpx;
  text-align: center;
  z-index: 10;
}

.song-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 8rpx;
  display: block;
}

.song-artist {
  font-size: 28rpx;
  color: #a3a3a3;
  display: block;
}

/* 歌词区域 */
.lyrics-section {
  height: 360rpx;
  background-color: rgba(0, 0, 0, 0.3);
  position: relative;
}

.lyrics-container {
  height: 100%;
  padding: 10rpx;
  position: relative;
}

.lyrics-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 0;
  position: relative;
  min-height: 100%;
  justify-content: center;
}

.lyrics-line {
  text-align: center;
  padding: 12rpx 0;
  font-size: 26rpx;
  color: #a3a3a3;
  display: block;
  transition: all 0.3s;
}

.lyrics-line.active {
  color: #3b82f6;
  font-size: 30rpx;
  font-weight: bold;
  transform: scale(1.05);
}

/* 进度条 */
.progress-section {
  padding: 20rpx 40rpx;
}

.time-display {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10rpx;
}

.time-text {
  font-size: 24rpx;
  color: #a3a3a3;
}

.progress-bar {
  position: relative;
  height: 6rpx;
  border-radius: 6rpx;
  overflow: hidden;
}

.progress-bg {
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: #4b5563;
}

.progress-fill {
  position: absolute;
  height: 100%;
  background: linear-gradient(to right, #3b82f6, #8b5cf6);
  transition: width 0.1s;
}

.progress-handle {
  position: absolute;
  width: 16rpx;
  height: 16rpx;
  background-color: #ffffff;
  border-radius: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.5);
}

/* 控制按钮 */
.controls-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 40rpx;
}

.control-btn {
  opacity: 0.7;
}

.control-btn.active {
  color: #3b82f6;
  opacity: 1;
}

.play-btn {
  width: 100rpx;
  height: 100rpx;
  background-color: #3b82f6;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 8rpx 15rpx rgba(59, 130, 246, 0.3);
}

.play-btn.disabled {
  background-color: #6b7280;
  box-shadow: none;
  opacity: 0.6;
}

.uni-icon {
  font-family: "uniicons";
  font-size: 48rpx;
}

/* 注释掉相似歌曲区域样式
/* 相似歌曲区域 */
/*
.similar-section {
  padding: 20rpx 40rpx;
  border-top: 2rpx solid #333333;
}

.similar-title {
  font-size: 28rpx;
  color: #a3a3a3;
  margin-bottom: 20rpx;
  display: block;
}

.similar-list {
  display: flex;
  flex-direction: column;
}

.similar-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 2rpx solid #333333;
}

.similar-cover {
  width: 80rpx;
  height: 80rpx;
  border-radius: 10rpx;
  margin-right: 20rpx;
}

.similar-info {
  flex: 1;
  min-width: 0;
}

.similar-name {
  font-size: 28rpx;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}

.similar-artist {
  font-size: 24rpx;
  color: #a3a3a3;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: block;
}
*/

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.rotating {
  animation: rotate 20s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}
</style>    